package com.quanyan.common.exception.handler;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.exception.BizException;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 *
 * spring boo 全局异常捕获
 * @author songzj
 * @date 16/4/15-11:01
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = {BizException.class, RuntimeException.class})
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ResponseEntity<?> internalExceptionHandler(RuntimeException e) {
        logger.error("internalExceptionHandler: stacktrace={}", ExceptionUtils.getStackTrace(e));
        if (e instanceof BizException){
            BizException bizException = (BizException)e;
            if (bizException.getApiResponseEnum() == null){
                APIResponse response = APIResponse.returnFail(bizException.getErrorData(), bizException.getMessage());

                return new ResponseEntity(response, HttpStatus.OK);
            }
            return new ResponseEntity(APIResponse.returnFail(bizException.getErrorData(), bizException.getApiResponseEnum()), HttpStatus.OK);
        }
        int code = HttpStatus.BAD_REQUEST.value();
        String message = e.getCause().getMessage();
        return new ResponseEntity(APIResponse.returnFail(code,message), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseEntity<?> exceptionHandler(Exception e) {
        logger.error("exceptionHandler: stacktrace={}", ExceptionUtils.getStackTrace(e));
        return new ResponseEntity(APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
    }









}
